/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.gateway.dianlan.bits;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import info.peigen.hotpot.common.service.base.exception.BusinessException;
import info.peigen.hotpot.component.gateway.core.util.HexUtil;
import info.peigen.hotpot.component.gateway.dianlan.bits.base.BitParserBase;
import info.peigen.hotpot.component.gateway.dianlan.facade.enums.DianlanBatteryPackStatus;
import info.peigen.hotpot.component.gateway.dianlan.protocol.passive.DianlanBatteryPackStatusInfo;

/**
 * <b>(DianlanBatteryPackStatusInfoParserBits)</b>
 * <p>
 * 电池组状态解析
 *
 * @author LiDaHai
 * @version 1.0.0
 * @since 2023/1/12
 */
public class DianlanBatteryPackStatusInfoParserBits extends BitParserBase {

    public DianlanBatteryPackStatusInfo parseReason(String hexString) {
        String[] hexStrArray = hexStrToArray(hexString);
        Assert.isTrue(hexStrArray.length == 8, () -> new BusinessException("[DianlanBatteryPackStatusInfoParserBits]数据解析异常，字节未对齐"));
        DianlanBatteryPackStatusInfo batteryPackStatusInfo = DianlanBatteryPackStatusInfo.builder().build();
        batteryPackStatusInfo.setBatteryPackTotalVoltage(0.1d * parseInt(hexStrArray[1] + hexStrArray[0]));
        batteryPackStatusInfo.setBatteryPackTotalCurrent(0.05d * parseInt(hexStrArray[3] + hexStrArray[2]) + (-1200));
        batteryPackStatusInfo.setBatteryPackCapacitySOC(0.4d * parseInt(hexStrArray[4]));
        String bitString = HexUtil.hexToBinary(hexStrArray[5]);
        batteryPackStatusInfo.setBatteryPackStatus(parseBatterPackStatus(StrUtil.sub(bitString, 0, 4)));
        batteryPackStatusInfo.setReserve2(StrUtil.sub(bitString, 5, 5));
        batteryPackStatusInfo.setReserve1(StrUtil.sub(bitString, 6, 7));
        batteryPackStatusInfo.setBatteryPackCntCount(parseInt(hexStrArray[6]));
        bitString = HexUtil.hexToBinary(hexStrArray[7]);
        batteryPackStatusInfo.setBatteryPackFaultCode(parseInt(StrUtil.sub(bitString, 0, 2)) + "");
        batteryPackStatusInfo.setBatteryPackFaultLevel(parseInt(StrUtil.sub(bitString, 2, 7)) + "");
        return batteryPackStatusInfo;
    }

    private DianlanBatteryPackStatus parseBatterPackStatus(String bits) {
        switch (bits) {
            case "0000":
                return DianlanBatteryPackStatus.PowerOn;
            case "0110":
                return DianlanBatteryPackStatus.AutoWakeUp;
            case "1000":
                return DianlanBatteryPackStatus.Available;
            case "1100":
                return DianlanBatteryPackStatus.Change;
            case "1010":
                return DianlanBatteryPackStatus.UnChange;
            default:
                return DianlanBatteryPackStatus.UNKNOWN;
        }
    }
}